package com.xnew.aes;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * 前后端数据传输加密工具类
 * @author monkey
 *
 */
public class AesEncryptUtils {
    //可配置到Constant中，并读取配置文件注入,16位,自己定义
    public static final String KEY = "xlen5Px9V6rjzi4z";
 
    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
 
    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);
 
    }
 
    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }
 
    public static String encrypt(String content) throws Exception {
        return encrypt(content, KEY);
    }
    public static String decrypt(String encryptStr) throws Exception {
        return decrypt(encryptStr, KEY);
    }
 
    /**
     * 解密  用于与移动办公平台交互
     * @param sSrc 接收到的加密过后的字符串（带解密密文）
     * @param sKey 秘钥
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc, String sKey,String iv) throws Exception {
        try {
            if (sKey == null) {
                System.out.print("Key不能为空null");
                return null;
            }
            if (sKey.length() != 16) {
                System.out.print("Key的长度不是16位");
                return null;
            }
            if (iv.length() != 16) {
                System.out.print("iv的长度不是16位");
                return null;
            }
            byte[] byte1 = Base64.decodeBase64(sSrc.getBytes());//先用Base64解码
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
            SecretKeySpec key = new SecretKeySpec(sKey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
            //与加密时不同MODE:Cipher.DECRYPT_MODE
            byte[] ret = cipher.doFinal(byte1);
            return new String(ret, "utf-8");
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
 
    public static void main(String[] args) throws Exception {
//        Map map=new HashMap<String,String>();
//        map.put("key","value");
//        map.put("中文","汉字");
//        String content = JSONObject.toJSONString(map);
//        System.out.println("加密前：" + content);
// 
//        String encrypt = encrypt(content, KEY);
//        System.out.println("加密后：" + encrypt);
// 
//        String decrypt = decrypt("dtWmC2jNFYQwlCBL5T3B/EnZyOQ6Arqu+SS5rdop03UwSAH1ub2fAiTEqdldREjY", KEY);
//        System.out.println("解密后：" + decrypt);
    }
    
}